﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace SIA.HwAccess.PLCSiemens
{   
    /// <summary>Descive l'intera area dati associata ad un collegamento, è formata da N subAree con N = il numero di DataBlock</summary>
    public class CompactHwAddressCollection : List<IHwAddress>
    {

        public new void Add(IHwAddress hwAddress)
        {
            if (this.Contains(hwAddress)) return;

            foreach (IHwAddress ha in this)
            {
                if (ha.Contains(hwAddress)) return;
                if (ha.Adjacent(hwAddress))
                {
                    ha.Merge(hwAddress);
                    //eventuali compressioni
                    compactAddressList();
                    return;
                }
            }

            base.Add(new S7HwAddress(hwAddress));
        }

        private void compactAddressList()
        {
            List<IHwAddress> removedAddress = new List<IHwAddress>();

            foreach (IHwAddress ha1 in this)
                foreach (IHwAddress ha2 in this)
                    if (this.IndexOf(ha1) != this.IndexOf(ha2))
                        if (ha1.Adjacent(ha2))
                        {
                            ha1.Merge(ha2);
                            removedAddress.Add(ha2);
                        }

            foreach (IHwAddress ha in removedAddress)
            {
                if (this.Contains(ha))
                    this.Remove(ha);
            }
        }
        public override string ToString()
        {
            String str = base.ToString() + "-> " ;
            foreach (IHwAddress ha in this)
            {
                str = str + ha.ToString() + "|";
            }
            return str;
        }
    }
}
